package com.sfac.javaSpringBoot.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

//设置监听器

@WebListener
public class LogDestroyListener implements ServletContextListener {
                                                                //类名.class
    private final static Logger LOGGER = LoggerFactory.getLogger(LogDestroyListener.class);



    @Override
    public void contextInitialized(ServletContextEvent sce) {
        LOGGER.debug("==== Init Context ====");

        File destFolder = new File("/log");
        if (destFolder==null || !destFolder.exists()){
            return;
        }
//        判断文件是否当前日期不是就删除
        DateTimeFormatter dtf =   DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String currentDate = dtf.format(LocalDateTime.now());

         File[] files = destFolder.listFiles();
         for (File file:files){
             String fileName = file.getName();
             if (!fileName.contains(currentDate)){
                 file.delete();
             }
         }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        LOGGER.debug("==== Destroy Context ====");
    }
}
